package com.wyp.didishige.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ImageView;

import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.wyp.didishige.MyApplication;
import com.wyp.didishige.MyMessageReceiver;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.fragment.DiscoverFragment;
import com.wyp.didishige.fragment.NearBoyFragment;
import com.wyp.didishige.fragment.NearFragment;
import com.wyp.didishige.fragment.RecentFragment;
import com.wyp.didishige.fragment.SettingsFragment;
import com.wyp.didishige.model.Dynamic;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.PreferenceHelper;
import com.wyp.didishige.wiget.ChangeColorIconWithTextView;
import com.wyp.didishige.R;
import com.wyp.didishige.model.User;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.im.BmobChat;
import cn.bmob.im.BmobChatManager;
import cn.bmob.im.BmobNotifyManager;
import cn.bmob.im.bean.BmobInvitation;
import cn.bmob.im.bean.BmobMsg;
import cn.bmob.im.config.BmobConfig;
import cn.bmob.im.db.BmobDB;
import cn.bmob.im.inteface.EventListener;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.FindListener;


public class MainActivity extends BaseActivity
        implements EventListener, View.OnClickListener, ViewPager.OnPageChangeListener {
    public final static int MSG_REFRESH_DYNAMIC_CODE = 0;

    FragmentManager fragmentManager;
    BmobGeoPoint bmobGeoPoint;
    User user;
    private ViewPager mViewPager;
    private List<Fragment> mTabs = new ArrayList<Fragment>();
    private FragmentPagerAdapter mAdapter;

    private NearBoyFragment nearBoyFragment;
    private DiscoverFragment discoverFragment;
    private RecentFragment recentFragment;
    private NearFragment nearFragment;
    private SettingsFragment settingFragment;
    //    ImageView iv_recent_tips, iv_contact_tips;//消息提示
    private List<ChangeColorIconWithTextView> mTabIndicator = new ArrayList<ChangeColorIconWithTextView>();

    private ImageView msgTips = null;
    private ImageView newInviteTips = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setOverflowShowingAlways();
        actionBar = getSupportActionBar();

        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);

        //开启定时检测服务（单位为秒）-在这里检测后台是否还有未读的消息，有的话就取出来
        //如果你觉得检测服务比较耗流量和电量，你也可以去掉这句话-同时还有onDestory方法里面的stopPollService方法
        BmobChat.getInstance(this).startPollService(10);

        user = userManager.getCurrentUser(User.class);

        fragmentManager = getSupportFragmentManager();
        if (user != null) {
            user.setLastLogin(System.currentTimeMillis());
            user.update(this);
        } else {
            IntentUtil.start_activity(this, LoginActivity.class);
        }

        initNewMessageBroadCast();
        initTagMessageBroadCast();
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        initTab();
        dynamicIsEmpty();
    }

    private void initTabIndicator() {
        ChangeColorIconWithTextView one = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_one);
        ChangeColorIconWithTextView two = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_two);
        ChangeColorIconWithTextView three = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_three);
        ChangeColorIconWithTextView four = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_four);
        msgTips = (ImageView) findViewById(R.id.msgTips);
        newInviteTips = (ImageView) findViewById(R.id.newInviteTips);

        mTabIndicator.add(one);
        mTabIndicator.add(two);
        mTabIndicator.add(three);
        mTabIndicator.add(four);

        one.setOnClickListener(this);
        two.setOnClickListener(this);
        three.setOnClickListener(this);
        four.setOnClickListener(this);

        one.setIconAlpha(1.0f);
    }

    private void initTab() {
        discoverFragment = new DiscoverFragment();


        recentFragment = new RecentFragment();

        settingFragment = new SettingsFragment();
        if (PreferenceHelper.readBoolean(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false)) {
            nearFragment = NearFragment.newInstance(false);
            mTabs.add(nearFragment);
            mTabs.add(discoverFragment);
        } else {
            nearFragment = new NearFragment();
            mTabs.add(discoverFragment);
            mTabs.add(nearFragment);
        }

        mTabs.add(recentFragment);
        mTabs.add(settingFragment);

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return mTabs.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mTabs.get(arg0);
            }
        };

        initTabIndicator();

        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setOnPageChangeListener(this);

    }

    @Override
    public void onPageSelected(int arg0) {
        supportInvalidateOptionsMenu();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
        if (positionOffset > 0) {
            ChangeColorIconWithTextView left = mTabIndicator.get(position);
            ChangeColorIconWithTextView right = mTabIndicator.get(position + 1);

            left.setIconAlpha(1 - positionOffset);
            right.setIconAlpha(positionOffset);
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {

        resetOtherTabs();

        switch (v.getId()) {
            case R.id.id_indicator_one:
                if (PreferenceHelper.readBoolean(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false)) {
                    MobclickAgent.onEvent(this, "main_near_click");
                } else {
                    MobclickAgent.onEvent(this, "main_discovr_click");
                }

                mTabIndicator.get(0).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(0, false);
                break;
            case R.id.id_indicator_two:

                if (PreferenceHelper.readBoolean(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false)) {
                    MobclickAgent.onEvent(this, "main_discovr_click");
                } else {
                    MobclickAgent.onEvent(this, "main_near_click");
                }

                mTabIndicator.get(1).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(1, false);
                break;
            case R.id.id_indicator_three:
                MobclickAgent.onEvent(this, "main_recent_click");
                mTabIndicator.get(2).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(2, false);
                break;
            case R.id.id_indicator_four:
                MobclickAgent.onEvent(this, "main_setting_click");
                mTabIndicator.get(3).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(3, false);
                break;

        }

    }

    /**
     * 重置其他的Tab
     */
    private void resetOtherTabs() {
        for (int i = 0; i < mTabIndicator.size(); i++) {
            mTabIndicator.get(i).setIconAlpha(0);
        }
    }


    NewBroadcastReceiver newReceiver;

    private void initNewMessageBroadCast() {
        // 注册接收消息广播
        newReceiver = new NewBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(BmobConfig.BROADCAST_NEW_MESSAGE);
        //优先级要低于ChatActivity
        intentFilter.setPriority(3);
        registerReceiver(newReceiver, intentFilter);
    }

    /**
     * 新消息广播接收者
     */
    private class NewBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //刷新界面
            refreshNewMsg(null);
            // 记得把广播给终结掉
            abortBroadcast();
        }
    }

    /**
     * 刷新界面
     */
    private void refreshNewMsg(BmobMsg message) {
        // 声音提示
        boolean isAllow = MyApplication.getInstance().getSpUtil().isAllowVoice();
        if (isAllow) {
            MyApplication.getInstance().getMediaPlayer().start();
        }

        //也要存储起来
        if (message != null) {
            BmobChatManager.getInstance(MainActivity.this).saveReceiveMessage(true, message);
        }
        if (mViewPager.getCurrentItem() == 2) {
            //当前页面如果为会话页面，刷新此页面
            if (recentFragment != null) {
                recentFragment.refresh();
            }
        } else {
            msgTips.setVisibility(View.VISIBLE);
        }
    }

    TagBroadcastReceiver userReceiver;

    private void initTagMessageBroadCast() {
        // 注册接收消息广播
        userReceiver = new TagBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(BmobConfig.BROADCAST_ADD_USER_MESSAGE);
        //优先级要低于ChatActivity
        intentFilter.setPriority(3);
        registerReceiver(userReceiver, intentFilter);
    }

    /**
     * 标签消息广播接收者
     */
    private class TagBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            BmobInvitation message = (BmobInvitation) intent.getSerializableExtra("invite");
            refreshInvite(message);
            // 记得把广播给终结掉
            abortBroadcast();
        }
    }

    /**
     * 刷新好友请求
     *
     * @param @param message
     * @return void
     * @throws
     * @Title: notifyAddUser
     * @Description: TODO
     */
    private void refreshInvite(BmobInvitation message) {
        boolean isAllow = MyApplication.getInstance().getSpUtil().isAllowVoice();
        if (isAllow) {
            MyApplication.getInstance().getMediaPlayer().start();
        }
        msgTips.setVisibility(View.VISIBLE);
        //同时提醒通知
        String tickerText = "有窝友请求添加好友";
        boolean isAllowVibrate = MyApplication.getInstance().getSpUtil().isAllowVibrate();
        BmobNotifyManager.getInstance(this).showNotify(isAllow, isAllowVibrate, R.drawable.ic_launcher,
                tickerText, "窝友", tickerText.toString(), NewFriendActivity.class);
    }

    /**
     * 隐藏tips
     */
    public void hiddenMsgTips() {
        msgTips.setVisibility(View.GONE);
    }

    public void refreshPoint(BmobGeoPoint point) {
        bmobGeoPoint = point;
    }

    @Override
    public void onOffline() {
        showOfflineDialog(this);
    }

    /**
     * 用户动态是否为空
     */
    private void dynamicIsEmpty() {
        BmobQuery<Dynamic> query = new BmobQuery<Dynamic>();
        query.addWhereEqualTo("authorId", userManager.getCurrentUser().getObjectId());
        query.findObjects(this, new FindListener<Dynamic>() {
            @Override
            public void onSuccess(List<Dynamic> list) {
                if (list == null || list.isEmpty()) {
                    if (!PreferenceHelper.readBoolean(MainActivity.this,Config.PreferenceHelperfile,Config.KEY_NEW_FIRSTER_DYNAMIC,false)){
                        PreferenceHelper.write(MainActivity.this,Config.PreferenceHelperfile,Config.KEY_NEW_FIRSTER_DYNAMIC,true);
                        Bundle bundle = new Bundle();
                        bundle.putBoolean(Config.KEY_NEW_FIRSTER_DYNAMIC, true);
                        IntentUtil.start_activity(MainActivity.this, NewDynamicActivity.class, bundle);
                        finish();
                    }

                }
            }

            @Override
            public void onError(int i, String s) {
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (PreferenceHelper.readBoolean(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false)) {
            if (mViewPager.getCurrentItem() == 0) {
                getMenuInflater().inflate(R.menu.menu_nearpeople_activity, menu);
            }
        } else {
            if (mViewPager.getCurrentItem() == 1) {
                getMenuInflater().inflate(R.menu.menu_nearpeople_activity, menu);
            }
        }

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case android.R.id.home:
                break;
            case R.id.logout:
                break;
            case R.id.about:
                break;
            case R.id.action_all:
                MobclickAgent.onEvent(this, "recent_right_top_all_click");
                nearFragment.setSex(null);
                break;
            case R.id.action_female:
                MobclickAgent.onEvent(this, "recent_right_top_female_click");
                nearFragment.setSex(false);
                break;
            case R.id.action_male:
                MobclickAgent.onEvent(this, "recent_right_top_male_click");
                nearFragment.setSex(true);
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            unregisterReceiver(newReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(userReceiver);
        } catch (Exception e) {
        }
        //取消定时检测服务
        BmobChat.getInstance(this).stopPollService();
    }

    long firsttime;

    @Override
    public void onBackPressed() {
//        if (firsttime + 2000 > System.currentTimeMillis()) {
        MobclickAgent.onKillProcess(this);
        finish();
//        } else {
//            ShowToast("再按一次退出程序");
//        }
//        firsttime = System.currentTimeMillis();
    }

    @Override
    public void onResume() {
        super.onResume();
        //小圆点提示
        if (BmobDB.create(this).hasUnReadMsg()) {
            msgTips.setVisibility(View.VISIBLE);
        } else {
            msgTips.setVisibility(View.GONE);
        }

        if (BmobDB.create(this).hasNewInvite()) {
            newInviteTips.setVisibility(View.VISIBLE);
        } else {
            newInviteTips.setVisibility(View.GONE);
        }

        MyMessageReceiver.ehList.add(this);// 监听推送的消息
        //清空
        MyMessageReceiver.mNewNum = 0;
    }

    @Override
    public void onPause() {
        super.onPause();
        MyMessageReceiver.ehList.remove(this);// 取消监听推送的消息
    }

    @Override
    public void onMessage(BmobMsg bmobMsg) {
        refreshNewMsg(bmobMsg);
    }

    @Override
    public void onReaded(String s, String s2) {

    }

    @Override
    public void onNetChange(boolean isNetConnected) {
        if (isNetConnected) {
            ShowToast(R.string.network_tips);
        }
    }

    @Override
    public void onAddUser(BmobInvitation message) {
        refreshInvite(message);
    }

    private void setOverflowShowingAlways() {
        try {
            // true if a permanent menu key is present, false otherwise.
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case MSG_REFRESH_DYNAMIC_CODE:
                    discoverFragment.onRefresh();
                    break;
            }
        }
    }
}
